<template>
    <div class="app-container">
        <el-tabs v-model="activeName" type="card">
            <el-tab-pane :label="reviewingTitle" name="first">
                <template v-cloak v-if="activeName === 'first'">
                    <div class="filter-container">
                        <el-input v-model="query.eat_name" class="filter-item w-200" size="medium" placeholder="申请人姓名"></el-input>
                        <el-input v-model="query.eat_phone" class="filter-item w-200" size="medium" placeholder="申请人电话"></el-input>
                        <el-select class="filter-item w-200" size="medium" v-model="query.eat_type" clearable placeholder="订餐类型">
                            <el-option label="早餐" value="1"></el-option>
                            <el-option label="午餐" value="2"></el-option>
                            <el-option label="晚餐" value="3"></el-option>
                        </el-select>
                        <div class="filter-item block">
                            <el-date-picker
                                    size="medium"
                                    v-model="query.eat_date"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="订餐日期">
                            </el-date-picker>
                        </div>
                        <el-select class="filter-item w-200" size="medium" v-model="query.status" clearable placeholder="订单状态">
                            <el-option label="已提交" value="10"></el-option>
                            <el-option label="制作中" value="20"></el-option>
                            <el-option label="已完成" value="30"></el-option>
                            <el-option label="已取消" value="40"></el-option>
                        </el-select>
                        <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(true)">搜 索</el-button>
                        <el-button class="filter-item" size="medium" icon="el-icon-download" @click="downloadOrder(query.is_review)">导出订单</el-button>
                    </div>
                    <el-table v-loading="loading" :data="orders" border style="width: 100%">
                        <el-table-column width="50px" label="#" align="center">
                            <template slot-scope="scope" >
                                {{query.size * (query.page-1) + scope.$index + 1}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="eat_name" label="申请人姓名" align="center"></el-table-column>
                        <el-table-column prop="eat_phone" label="申请人电话" align="center"></el-table-column>
                        <el-table-column label="订餐类型" align="center">
                            <template slot-scope="scope" >
                                <span v-if="scope.row.rule.eat_type === 1">早餐</span>
                                <span v-if="scope.row.rule.eat_type === 2">午餐</span>
                                <span v-if="scope.row.rule.eat_type === 3">晚餐</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="订餐日期" align="center">
                            <template slot-scope="scope" >
                                {{ scope.row.rule.eat_date }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status_label" label="订单状态" align="center"></el-table-column>
                        <el-table-column prop="type_label" label="订单类型" align="center"></el-table-column>
                        <el-table-column prop="review.person_info" label="人员信息" align="center"></el-table-column>
                        <el-table-column prop="review.person_num" label="人数" align="center"></el-table-column>
                        <el-table-column prop="review.reason" label="加餐事由" align="center"></el-table-column>
                        <el-table-column prop="review.remark" label="备注" align="center"></el-table-column>
                        <el-table-column prop="created_at" width="160px" label="下单时间" align="center"></el-table-column>
                        <el-table-column label="操作" align="center" width="220px">
                            <template slot-scope="scope">
                                <el-button v-if="scope.row.status === 10 && scope.row.review && scope.row.review.status === 10" class="filter-item" icon="el-icon-edit" type="primary" size="mini" @click="showReview(scope.row, 20)">通过</el-button>
                                <el-button v-if="scope.row.status === 10 && scope.row.review && scope.row.review.status === 10" class="filter-item" icon="el-icon-close" type="danger" size="mini" @click="showReview(scope.row, 30)">拒绝</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="query.page"
                                :page-sizes="[10, 20, 30, 50]"
                                :page-size="query.size"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                        </el-pagination>
                    </div>
                </template>
            </el-tab-pane>
            <el-tab-pane :label="reviewedTitle" name="second">
                <template v-cloak v-if="activeName === 'second'">
                    <div class="filter-container">
                        <el-input v-model="queryReviewed.eat_name" class="filter-item w-200" size="medium" placeholder="申请人姓名"></el-input>
                        <el-input v-model="queryReviewed.eat_phone" class="filter-item w-200" size="medium" placeholder="申请人电话"></el-input>
                        <el-select class="filter-item w-200" size="medium" v-model="queryReviewed.eat_type" clearable placeholder="订餐类型">
                            <el-option label="早餐" value="1"></el-option>
                            <el-option label="午餐" value="2"></el-option>
                            <el-option label="晚餐" value="3"></el-option>
                        </el-select>
                        <div class="filter-item block">
                            <el-date-picker
                                    size="medium"
                                    v-model="queryReviewed.eat_date"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="订餐日期">
                            </el-date-picker>
                        </div>
                        <el-select class="filter-item w-200" size="medium" v-model="queryReviewed.status" clearable placeholder="订单状态">
                            <el-option label="已提交" value="10"></el-option>
                            <el-option label="制作中" value="20"></el-option>
                            <el-option label="已完成" value="30"></el-option>
                            <el-option label="已取消" value="40"></el-option>
                        </el-select>
                        <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchListReviewed(true)">搜 索</el-button>
                        <el-button class="filter-item" size="medium" icon="el-icon-download" @click="downloadOrder(queryReviewed.is_review)">导出订单</el-button>
                    </div>
                    <el-table v-loading="loadingReviewed" :data="ordersReviewed" border style="width: 100%">
                        <el-table-column width="50px" label="#" align="center">
                            <template slot-scope="scope" >
                                {{queryReviewed.size * (queryReviewed.page-1) + scope.$index + 1}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="eat_name" label="申请人姓名" align="center"></el-table-column>
                        <el-table-column prop="eat_phone" label="申请人电话" align="center"></el-table-column>
                        <el-table-column label="订餐类型" align="center">
                            <template slot-scope="scope" >
                                <span v-if="scope.row.rule.eat_type === 1">早餐</span>
                                <span v-if="scope.row.rule.eat_type === 2">午餐</span>
                                <span v-if="scope.row.rule.eat_type === 3">晚餐</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="订餐日期" align="center">
                            <template slot-scope="scope" >
                                {{ scope.row.rule.eat_date }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status_label" label="订单状态" align="center"></el-table-column>
                        <el-table-column prop="type_label" label="订单类型" align="center"></el-table-column>
                        <el-table-column prop="review.person_info" label="人员信息" align="center"></el-table-column>
                        <el-table-column prop="review.person_num" label="人数" align="center"></el-table-column>
                        <el-table-column prop="review.reason" label="加餐事由" align="center"></el-table-column>
                        <el-table-column prop="review.remark" label="备注" align="center"></el-table-column>
                        <el-table-column prop="created_at" width="160px" label="下单时间" align="center"></el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                @size-change="handleSizeChangeReviewed"
                                @current-change="handleCurrentChangeReviewed"
                                :current-page="queryReviewed.page"
                                :page-sizes="[10, 20, 30, 50]"
                                :page-size="queryReviewed.size"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="totalReviewed">
                        </el-pagination>
                    </div>
                </template>
            </el-tab-pane>
            <el-tab-pane :label="refusedTitle" name="third">
                <template v-cloak v-if="activeName === 'third'">
                    <div class="filter-container">
                        <el-input v-model="queryRefused.eat_name" class="filter-item w-200" size="medium" placeholder="申请人姓名"></el-input>
                        <el-input v-model="queryRefused.eat_phone" class="filter-item w-200" size="medium" placeholder="申请人电话"></el-input>
                        <el-select class="filter-item w-200" size="medium" v-model="queryRefused.eat_type" clearable placeholder="订餐类型">
                            <el-option label="早餐" value="1"></el-option>
                            <el-option label="午餐" value="2"></el-option>
                            <el-option label="晚餐" value="3"></el-option>
                        </el-select>
                        <div class="filter-item block">
                            <el-date-picker
                                    size="medium"
                                    v-model="queryRefused.eat_date"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="订餐日期">
                            </el-date-picker>
                        </div>
                        <el-select class="filter-item w-200" size="medium" v-model="queryRefused.status" clearable placeholder="订单状态">
                            <el-option label="已提交" value="10"></el-option>
                            <el-option label="制作中" value="20"></el-option>
                            <el-option label="已完成" value="30"></el-option>
                            <el-option label="已取消" value="40"></el-option>
                        </el-select>
                        <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchListRefused(true)">搜 索</el-button>
                        <el-button class="filter-item" size="medium" icon="el-icon-download" @click="downloadOrder(queryRefused.is_review)">导出订单</el-button>
                    </div>
                    <el-table v-loading="loadingRefused" :data="ordersRefused" border style="width: 100%">
                        <el-table-column width="50px" label="#" align="center">
                            <template slot-scope="scope" >
                                {{queryRefused.size * (queryRefused.page-1) + scope.$index + 1}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="eat_name" label="申请人姓名" align="center"></el-table-column>
                        <el-table-column prop="eat_phone" label="申请人电话" align="center"></el-table-column>
                        <el-table-column label="订餐类型" align="center">
                            <template slot-scope="scope" >
                                <span v-if="scope.row.rule.eat_type === 1">早餐</span>
                                <span v-if="scope.row.rule.eat_type === 2">午餐</span>
                                <span v-if="scope.row.rule.eat_type === 3">晚餐</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="订餐日期" align="center">
                            <template slot-scope="scope" >
                                {{ scope.row.rule.eat_date }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status_label" label="订单状态" align="center"></el-table-column>
                        <el-table-column prop="type_label" label="订单类型" align="center"></el-table-column>
                        <el-table-column prop="review_message" label="拒绝理由" align="center"></el-table-column>
                        <el-table-column prop="review.person_info" label="人员信息" align="center"></el-table-column>
                        <el-table-column prop="review.person_num" label="人数" align="center"></el-table-column>
                        <el-table-column prop="review.reason" label="加餐事由" align="center"></el-table-column>
                        <el-table-column prop="review.remark" label="备注" align="center"></el-table-column>
                        <el-table-column prop="created_at" width="160px" label="下单时间" align="center"></el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                @size-change="handleSizeChangeRefused"
                                @current-change="handleCurrentChangeRefused"
                                :current-page="queryRefused.page"
                                :page-sizes="[10, 20, 30, 50]"
                                :page-size="queryRefused.size"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="totalRefused">
                        </el-pagination>
                    </div>
                </template>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
  import { fetchOrderReviews, reviewOrder } from '@/api/book-order'
  export default {
    name: 'review',
    data() {
      return {
        activeName: 'first',
        loading: false,
        loadingReviewed: false,
        loadingRefused: false,
        orders: [],
        ordersReviewed: [],
        ordersRefused: [],
        title: '',
        total: 0,
        totalReviewed: 0,
        totalRefused: 0,
        query: {
          type: '',
          size: 10,
          page: 1,
          status: '',
          eat_name: '',
          eat_phone: '',
          eat_type: '',
          eat_date: '',
          is_review: 10
        },
        queryReviewed: {
          type: '',
          size: 10,
          page: 1,
          status: '',
          eat_name: '',
          eat_phone: '',
          eat_type: '',
          eat_date: '',
          is_review: 20
        },
        queryRefused: {
          type: '',
          size: 10,
          page: 1,
          status: '',
          eat_name: '',
          eat_phone: '',
          eat_type: '',
          eat_date: '',
          is_review: 30
        }
      }
    },
    computed: {
      reviewingTitle() {
        return '审核中(' + this.total + ')'
      },
      reviewedTitle() {
        return '已通过(' + this.totalReviewed + ')'
      },
      refusedTitle() {
        return '未通过(' + this.totalRefused + ')'
      }
    },
    methods: {
      // 审核
      showReview(row, status) {
        if (status === 20) {
          // pass
          this.$confirm('通过审核?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            reviewOrder({ status: status }, row.id).then(res => {
              if (res.result === 'failed') {
                this.$message.error(res.msg)
              } else {
                this.$message.success('审核通过!')
                this.fetchList()
                this.fetchListReviewed()
                this.fetchListRefused()
              }
            }).catch(err => {
              this.$handleNotFound(err, '订单不存在')
            })
          }).catch(() => {})
        } else {
          // refuse
          this.title = '请填写拒绝理由'
          this.$prompt(this.title, '审核订单', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(({ value }) => {
            reviewOrder({ status: status, message: value }, row.id).then(res => {
              if (res.result === 'failed') {
                this.$message.error(res.msg)
              } else {
                this.$message.success('审核成功')
                this.fetchList()
                this.fetchListReviewed()
                this.fetchListRefused()
              }
            }).catch(err => {
              this.$handleNotFound(err, '订单不存在')
            })
          }).catch(() => {})
        }
      },
      handleSizeChange(size) {
        this.query.size = size
        this.fetchList()
      },
      handleCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      handleSizeChangeReviewed(size) {
        this.queryReviewed.size = size
        this.fetchListReviewed()
      },
      handleCurrentChangeReviewed(page) {
        this.queryReviewed.page = page
        this.fetchListReviewed()
      },
      handleSizeChangeRefused(size) {
        this.queryRefused.size = size
        this.fetchListRefused()
      },
      handleCurrentChangeRefused(page) {
        this.queryRefused.page = page
        this.fetchListRefused()
      },
      fetchList(resetPage = false) {
        this.query.type = ''
        if (resetPage) {
          this.query.page = 1
        }
        this.loading = true
        fetchOrderReviews(this.query).then(res => {
          this.orders = res.data
          this.total = res.meta.total
          this.loading = false
        })
      },
      fetchListReviewed(resetPage = false) {
        this.queryReviewed.type = ''
        if (resetPage) {
          this.queryReviewed.page = 1
        }
        this.loadingReviewed = true
        fetchOrderReviews(this.queryReviewed).then(res => {
          this.ordersReviewed = res.data
          this.totalReviewed = res.meta.total
          this.loadingReviewed = false
        })
      },
      fetchListRefused(resetPage = false) {
        this.queryRefused.type = ''
        if (resetPage) {
          this.queryRefused.page = 1
        }
        this.loadingRefused = true
        fetchOrderReviews(this.queryRefused).then(res => {
          this.ordersRefused = res.data
          this.totalRefused = res.meta.total
          this.loadingRefused = false
        })
      },
      // 导出订单
      downloadOrder(status) {
        this.$confirm('确定导出?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (status === 10) {
            this.exportOrder(this.query)
          } else if (status === 20) {
            this.exportOrder(this.queryReviewed)
          } else if (status === 30) {
            this.exportOrder(this.queryRefused)
          }
        }).catch(() => {})
      },
      exportOrder(row) {
        row.type = 'export'
        fetchOrderReviews(row).then(res => {
          if (res.length === 0) {
            this.$message('无数据')
          } else {
            const filename = this.$moment().format('YYYY-MM-DD') + '-' + parseInt(10000 * Math.random())
            const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' }
            const list = res
            const tHeader = ['学校', '申请人姓名', '申请人电话', '订餐类型', '订餐日期', '订单类型', '订单状态', '审核状态', '审核信息', '下单时间']
            const filterVal = ['school_name', 'eat_name', 'eat_phone', 'eat_type', 'eat_date', 'type_label', 'status_label', 'review_label', 'review_message', 'created_at']
            const data = this.formatJson(filterVal, list)
            data.unshift(tHeader)
            const wb = { SheetNames: [], Sheets: {}}
            const ws = this.sheet_from_array_of_arrays(data)
            ws['!cols'] = []
            for (let n = 0; n !== filterVal.length; ++n) {
              ws['!cols'].push({
                wpx: 100
              })
            }
            ws['!rows'] = [{ hpx: 20 }]
            wb.SheetNames.push(filename)
            wb.Sheets[filename] = ws
            const tmpDown = new Blob([this.s2ab(this.$xlsx.write(wb, wopts))], { type: 'application/octet-stream' })
            this.$fileSaver.saveAs(tmpDown, filename + '.xlsx')
          }
        })
      },
      sheet_from_array_of_arrays(data) {
        const ws = {}
        const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 }}
        for (let R = 0; R !== data.length; ++R) {
          for (let C = 0; C !== data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R
            if (range.s.c > C) range.s.c = C
            if (range.e.r < R) range.e.r = R
            if (range.e.c < C) range.e.c = C
            const cell = {
              v: data[R][C],
              s: {
                alignment: { horizontal: 'center', vertical: 'center' }
              }
            }
            if (cell.v == null) continue
            const cell_ref = this.$xlsx.utils.encode_cell({ c: C, r: R })
            if (typeof cell.v === 'number') {
              cell.t = 'n'
            } else if (typeof cell.v === 'boolean') {
              cell.t = 'b'
            } else if (cell.v instanceof Date) {
              cell.t = 'n'
              cell.z = this.$xlsx.SSF._table[14]
              cell.v = this.datenum(cell.v)
            } else {
              cell.t = 's'
            }
            ws[cell_ref] = cell
          }
        }
        if (range.s.c < 10000000) ws['!ref'] = this.$xlsx.utils.encode_range(range)
        return ws
      },
      datenum(v, date1904) {
        if (date1904) v += 1462
        const epoch = Date.parse(v)
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)
      },
      s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }
    },
    created() {
      this.fetchList()
      this.fetchListReviewed()
      this.fetchListRefused()
    }
  }
</script>

<style scoped>
    .el-icon-check{
        color: green;
    }
    .el-icon-close{
        color: red;
    }
</style>
